﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.DirectoryServices;
using Auction_Intranet.Models;
using AuctionDataLayer;
using Auction_Intranet.Helpers;
using System.Configuration;

namespace Auction_Intranet.Controllers
{
    [HandleError]
    public class ActionController : ParentController
    {
        DataRepository m_rep = new DataRepository();

        public ActionResult Help()
        {
            return View();
        }

        public ActionResult Error() 
        {
            return View();
        }

        public ActionResult Invitations()
        {
            var username = (User.Identity.Name).Split('\\')[1];
            var user = m_rep.GetUserByUsername(username);
            List<InvitationModel> model = new List<InvitationModel>();
            if (user != null)
            {
                
                IEnumerable<Invitation> invitations = m_rep.GetUserInvitationsByUserId(user.Id);
                foreach (var item in invitations)
                {
                    InvitationModel singleInvitation = new InvitationModel();
                    singleInvitation.invitation = item;
                    singleInvitation.groupMembers = m_rep.GetMembersOfGroupById(item.GroupId);
                    model.Add(singleInvitation);
                }
                return View(model);
            }
            return View();
        }

        public ActionResult AcceptInvitation(int? id)
        {
            if (id.HasValue)
            {
                int realId = id.Value;
                Invitation invitation = m_rep.GetInvitaionById(realId);
                if (invitation != null)
                {
                    AcceptInvitationModel model = new AcceptInvitationModel();
                    model.invitation = invitation;
                    return View(model);
                }
            }
            return View("NotFound");
        }

        [HttpPost]
        public ActionResult AcceptInvitation(AcceptInvitationModel model)
        {
            if (ModelState.IsValid)
            {                
                var username = (User.Identity.Name).Split('\\')[1];
                var user = m_rep.GetUserByUsername(username);         
                var invitation = m_rep.GetInvitaionById(model.invitation.Id);
                var group = m_rep.GetGroupById(model.invitation.GroupId);
                var status = m_rep.GetStateByName("Accepted");
                if (user != null && invitation != null && group != null && status != null)
                {
                    if (model.creditToAdd <= 0 || model.creditToAdd > user.Balance)
                    {
                        ModelState.AddModelError("creditToAdd", "Invalid credit amount");
                        return View(model);
                    }
                    //Update invitation Status to Accepted
                    m_rep.UpdateInvitationStatus(status.Id, invitation.Id);                 
                    //Update userbalance 
                    m_rep.UpdateGroupBalance(user.Balance - model.creditToAdd, user.MyGroupId);
                    m_rep.UpdateUserBalance(user.Balance - model.creditToAdd, user.Id);
                    m_rep.UpdateUserInGroupSpent(model.creditToAdd, user.Id, user.MyGroupId);
                    //Add user to userInGroup
                    m_rep.AddUserInGroup(user.Id, group.Id, model.creditToAdd);
                    //Update GroupBalance
                    m_rep.UpdateGroupBalance(group.Balance + model.creditToAdd, group.Id);

                    //if no invitations left redirest to groups
                    IEnumerable<Invitation> invitations = m_rep.GetUserInvitationsByUserId(user.Id);
                    if (invitations.Count() == 0)
                    {
                        return RedirectToAction("Index", "Groups");
                    }

                    return RedirectToAction("Invitations");
                }
                return View("Error");
            }
            return View(model);
        }
  
        public ActionResult DeclineInvitation(int? id)
        {
            if (id.HasValue)
            {
                int realId = id.Value;
                var username = (User.Identity.Name).Split('\\')[1];
                var user = m_rep.GetUserByUsername(username);
                var invitation = m_rep.GetInvitaionById(realId);
                var status = m_rep.GetStateByName("Declined");
                if (user != null && invitation != null && status != null)
                {
                    m_rep.UpdateInvitationStatus(status.Id, invitation.Id);
                    return RedirectToAction("Index","Dashboard");
                }
                return View("Error");               
            }
            return View("NotFound");
        }

        public ActionResult Notifications()
        {
            var username = (User.Identity.Name).Split('\\')[1];
            var user = m_rep.GetUserByUsername(username);
            IEnumerable<Notification> model;
            if (user != null)
            {
                model = m_rep.GetUserNotificationsByUserId(user.Id);
                return View(model);
            }
            return View();
        }

        public ActionResult DeleteNotification(int? id)
        {
            if (id.HasValue)
            {
                int realId = id.Value;
                var model = m_rep.GetNotificationById(realId);
                if (model != null)
                {
                    m_rep.DeleteNotification(model);
                    return RedirectToAction("Notifications");
                }
                return View("NotFound");
            }
            return View("NotFound");
        }

        [ChildActionOnly]
        public ActionResult _UserNotifications()
        {
            var username = (User.Identity.Name).Split('\\')[1];
            var user = m_rep.GetUserByUsername(username);
            UserNotificationsModel model = new UserNotificationsModel();
            if (user != null)
            {
                var invitations = m_rep.GetUserInvitationsByUserId(user.Id);
                var notifications = m_rep.GetUserNotificationsByUserId(user.Id);
                model.userInvitations = invitations.Take(3);
                model.userNotifications = notifications.Take(3);
                model.numberOfInvitations = invitations.Count();
                model.numberOfNotifications = notifications.Count();
                var current = DateTime.Now;
                if (current.Hour == 20)
                {
                    model.timeToClosure = "Bids closed";
                }
                else if (current.Hour > 21 && current.Hour < 24)
                {
                    var todayDate = DateTime.Now;
                    var remainingHours = 23 - todayDate.Hour;
                    var remainingMinutes = 59 - todayDate.Minute;
                    var remainingSeconds = 59 - todayDate.Second;
                    DateTime tempTime2 = new DateTime(2001, 1, 1, remainingHours+8, remainingMinutes, remainingSeconds);
                    model.timeToClosure = tempTime2.ToLongTimeString();
                }
                else if (current.Hour < 20)
                {
                    var todayDate = DateTime.Now;
                    var remainingHours = 19 - todayDate.Hour;
                    var remainingMinutes = 59 - todayDate.Minute;
                    var remainingSeconds = 59 - todayDate.Second;
                    DateTime tempTime2 = new DateTime(2001, 1, 1, remainingHours, remainingMinutes, remainingSeconds);
                    model.timeToClosure = tempTime2.ToLongTimeString();
                }                  
            }
            return PartialView(model);
        }

        [ChildActionOnly]
        public ActionResult _UserBalance()
        {
            var username = (User.Identity.Name).Split('\\')[1];
            User user = m_rep.GetUserByUsername(username);
            return PartialView(user);
        }

        //Backup
        public ActionResult MakeBid()
        {
            BidModel model = new BidModel();
            model.date = DateTime.Now;
            var EndBidDate = ConfigurationManager.AppSettings["EndingBiddingDate"];
            int endBidYear = Convert.ToInt32(EndBidDate.Split('.')[2]);
            int endBidMonth = Convert.ToInt32(EndBidDate.Split('.')[1]);
            int endBidDay = Convert.ToInt32(EndBidDate.Split('.')[0]);
            model.dateFinal = new DateTime(endBidYear,endBidMonth,endBidDay);

            if (DateTime.Now.Hour <= 20)
            {
                model.date = DateTime.Now.AddDays(1);
            }
            else
            {
                model.date = DateTime.Now.AddDays(2);
            }
            return View(model);
        }

        //Backup
        public ActionResult CreateGroup()
        {
            CreateGroupModel model = new CreateGroupModel();
            return View(model);
        }

        public ActionResult CollectUsernames(string query)
        {
            //we want all exept his own 
            var username = (User.Identity.Name).Split('\\')[1];
            User user = m_rep.GetUserByUsername(username);            
            if (user != null)
            {
                var users = m_rep.GetAllRUUsernamesFiltered(user.Username, query);
                List<object> results = new List<object>();
                foreach(var item in users)
                {
                    var temp = new { username = item.sUser, name = item.sName };
                    results.Add(temp);                    
                }
                return Json(results, JsonRequestBehavior.AllowGet);
            }
            return Json("", JsonRequestBehavior.AllowGet);                       
        }

        public ActionResult CheckUsername(string query)
        {            
            //we want all exept his own 
            var username = (User.Identity.Name).Split('\\')[1];
            User user = m_rep.GetUserByUsername(username);
            var userToAdd = m_rep.getRUUserByUserName(query);
            if (user != null && userToAdd != null)
            {
                if (user.Username != userToAdd.sUser)
                {
                    return Json(1);
                }                
            }
            return Json("");
        }
    }
}